<?php
/**
 * Mailview
 * http://code.google.com/p/mailview/
 * Martin Tournoij <martin@arp242.net>
 * Mailview is free for any use, there are no restrictions.
 */

include('mailview2.php');
$mailview = new Mailview2();

$vars = array();

if (!isset($_GET['mailbox']) and count($_POST) === 0)
	$_SESSION['mailbox'] = 'INBOX';

$link = Mailview\imap_open($_SESSION['config']);

### Button pressed, take action
if (isset($_POST['button']))
{
	# Expunge
	if ($_POST['button'] === 'expunge')
		Mailview\imap_expunge($link);
	elseif (isset($_POST['messages']))
	{
		ksort($_POST['messages']);
		array_reverse($_POST['messages']);

		foreach ($_POST['messages'] as $k => $v)
		{
			if ($v === 'on')
			{
				# Mark as read
				if ($_POST['button'] === 'read')
					Mailview\imap_setflag_full($link, (int) $k, '\Seen');
				# Mark for delete
				elseif ($_POST['button'] === 'delete')
				{
					Mailview\imap_setflag_full($link, (int) $k, '\Deleted');
					if (isset($_SESSION['config']['autoexpunge']))
						Mailview\imap_expunge($link);
				}
				# Mark as unread
				elseif ($_POST['button'] === 'unread')
					Mailview\imap_clearflag_full($link, (int) $k, '\Seen');
				# Mark as undelete
				elseif ($_POST['button'] === 'undelete')
					Mailview\imap_clearflag_full($link, (int) $k, '\Deleted');
				# Copy
				elseif ($_POST['button'] === 'Copy' and $_POST['newfolder'] != '')
					Mailview\imap_mail_copy($link, $k, $_POST['newfolder']);
				# Move
				elseif ($_POST['button'] === 'Move' and $_POST['newfolder'] != '')
				{
					Mailview\imap_mail_move($link, $k, $_POST['newfolder']);
					if (isset($_SESSION['config']['autoexpunge']))
						Mailview\imap_expunge($link);
				}
			}
		}
	}

	Redirect(array('mailbox' => $_SESSION['mailbox']));
}

$vars['nummsg'] = Mailview\imap_num_msg($link);
$vars['messages'] = Mailview\imap_fetch_overview($link, '1:' . $vars['nummsg'], Null, 1);

#if ($_SESSION['config']['threads'])
#	Mailview\imap_thread($vars['messages'], $_SESSION['config']['groupbysubject']);
#else
	Mailview\SortOverview($vars['messages'], $_SESSION['config']['sort']);

$mailview->Template($vars, $link);
?>
